package com.education.welco.controller.teacherapp;

import com.alibaba.fastjson.JSONObject;
import com.education.common.utils.ApiReturnObject;
import com.education.common.utils.StringUtils;
import com.education.welco.pojo.OrderPaper;
import com.education.welco.pojo.OrderPaperQuestion;
import com.education.welco.pojo.vo.OrderPaperVo;
import com.education.welco.service.OrderPaperQuestionService;
import com.education.welco.service.OrderPaperService;
import com.education.welco.service.OrderQuestionService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @Author: liftsail
 * @Date: 2023/1/8 15:53
 * @Description: 不积跬步无以至千里
 */
@RestController
@RequestMapping("/apptea/OrderPaper")
public class AppTeaOrderPaperController {

    @Autowired
    private OrderPaperService orderPaperService;

    @Autowired
    private OrderQuestionService orderQuestionService;

    @Autowired
    private OrderPaperQuestionService orderPaperQuestionService;

    private DateFormat yearMonthDayFormat = new SimpleDateFormat("yyyy年MM月dd日");

    //根据课程id查询试卷列表
    @GetMapping("/selectlist")
    public ApiReturnObject selectquestionlist(OrderPaper orderPaper, Integer pageSize, Integer pageNum) throws IOException {
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        List<OrderPaper> orderPapers = orderPaperService.selectOrderPaperList(orderPaper);
        for (OrderPaper paper : orderPapers) {
            paper.setStartTimeStr(yearMonthDayFormat.format((paper.getStartTime())));
            paper.setEndTimeStr(yearMonthDayFormat.format((paper.getEndTime())));
        }
        PageInfo<OrderPaper> pageInfo = new PageInfo<>(orderPapers);
        return new ApiReturnObject("200", "查询成功", pageInfo);
    }

    //老师发布试卷(随机组卷)
    @PostMapping("/publishPaper")
    //public ApiReturnObject publishPaper(OrderPaperVo orderPaper) {
    public ApiReturnObject publishPaper(@RequestParam("paper") String paper) {
        //rtype 是否可重新考试 0 不可以 1 可以  默认0
        OrderPaperVo orderPaper = JSONObject.parseObject(paper, OrderPaperVo.class);
        int length, sing, many, judg, answ;//试题总个数-length

        //2 随机出题 delFlag出题方式
        if ("2".equals(orderPaper.getDelFlag())) {
            //1 单选 2 判断 3 多选 4 简答   查询试题逻辑--查全部
            //查出所有单选题
            String[] sinIds = orderQuestionService.selectIdsByType(1);
            //查出所有判断题
            String[] judgIds = orderQuestionService.selectIdsByType(2);
            //查出所有多选题
            String[] manyIds = orderQuestionService.selectIdsByType(3);
            //查出所有简答题
            String[] answIds = orderQuestionService.selectIdsByType(4);

            if (Integer.parseInt(orderPaper.getSingle()) > sinIds.length) {
                //writeJSON(null, response, "201", "单选个数超出范围");
                return new ApiReturnObject("201", "单选题型数量不足", null);
            }
            if (Integer.parseInt(orderPaper.getMany()) > manyIds.length) {
                //writeJSON(null, response, "201", "多选个数超出范围");
                return new ApiReturnObject("201", "多选题型数量不足", null);
            }
            if (Integer.parseInt(orderPaper.getJudgment()) > judgIds.length) {
                //writeJSON(null, response, "201", "判断个数超出范围");
                return new ApiReturnObject("201", "判断题型数量不足", null);
            }
            if (Integer.parseInt(orderPaper.getAnsw()) > answIds.length) {
                //writeJSON(null, response, "201", "简答个数超出范围");
                return new ApiReturnObject("201", "简答题型数量不足", null);
            }
            //对应题型题目的集合
            List<Integer> danxuan = new ArrayList<>();//单
            List<Integer> duoxuan = new ArrayList<>();//多
            List<Integer> panduan = new ArrayList<>();//判
            List<Integer> jianda = new ArrayList<>();//简
            //试题总个数 length
            length = (sing = Integer.parseInt(orderPaper.getSingle())) + (many = Integer.parseInt(orderPaper.getMany())) + (judg = Integer.parseInt(orderPaper.getJudgment())) + (answ = Integer.parseInt(orderPaper.getAnsw()));
            //题目集合
            List<String> list = new ArrayList<>();
            for (int i = 0; i < sing; i++) {
                int i1 = random(Integer.parseInt(orderPaper.getSingle()), danxuan);
                list.add(sinIds[i1]);
            }
            for (int i = 0; i < many; i++) {
                int i2 = random(Integer.parseInt(orderPaper.getMany()), duoxuan);
                list.add(manyIds[i2]);
            }
            for (int i = 0; i < judg; i++) {
                int i3 = random(Integer.parseInt(orderPaper.getJudgment()), panduan);
                list.add(judgIds[i3]);
            }
            for (int i = 0; i < answ; i++) {
                int i4 = random(Integer.parseInt(orderPaper.getAnsw()), jianda);
                list.add(answIds[i4]);
            }
            String[] strings = list.toArray(new String[list.size()]);
            orderPaper.setQuestionIds(strings);

            //添加试卷
            Date date1 = new Date();
            SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format1 = dateFormat1.format(date1);
            orderPaper.setCreateTime(format1);//试卷创建日期
            //补充试卷的课程顶级id
            int i = orderPaperService.insertPaperTest(orderPaper);

            //添加试卷试题关联
            String[] questionIds = orderPaper.getQuestionIds();//试题集合数组
            for (int i1 = 0; i1 < questionIds.length; i1++) {
                OrderPaperQuestion orderPaperQuestion = new OrderPaperQuestion();//关联表对象
                orderPaperQuestion.setPaperId(orderPaper.getId());
                orderPaperQuestion.setQuestionId(Integer.parseInt(questionIds[i1]));
                orderPaperQuestionService.insertOrderPaperQuestion(orderPaperQuestion);
            }
            //writeJSON(null, response, "200", "添加成功");
            return new ApiReturnObject("添加成功", null);
        }

        //1 手动出题 delFlag出题方式
        if ("1".equals(orderPaper.getDelFlag())) {
            //把数组整合到一起
            String[] signarr = StringUtils.isNotEmpty(orderPaper.getSingleList()) ? orderPaper.getSingleList().split(",") : new String[0];//单选
            String[] manyarr = StringUtils.isNotEmpty(orderPaper.getManyList()) ? orderPaper.getManyList().split(",") : new String[0];//多选
            String[] judgarr = StringUtils.isNotEmpty(orderPaper.getJudgmentList()) ? orderPaper.getJudgmentList().split(",") : new String[0];//判断
            String[] answarr = StringUtils.isNotEmpty(orderPaper.getAnswList()) ? orderPaper.getAnswList().split(",") : new String[0];//简答
            length = (sing = signarr.length) + (many = manyarr.length) + (judg = judgarr.length) + (answ = answarr.length);
            String[] array = new String[length];//开辟空数组空间，保存id
            System.arraycopy(signarr, 0, array, 0, sing);
            System.arraycopy(manyarr, 0, array, sing, many);
            System.arraycopy(judgarr, 0, array, many + sing, judg);
            System.arraycopy(answarr, 0, array, many + sing + judg, answ);
            orderPaper.setQuestionIds(array);

            Date date1 = new Date();
            SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format1 = dateFormat1.format(date1);
            orderPaper.setCreateTime(format1);
            int i = orderPaperService.insertPaperTest(orderPaper);

            //添加试卷试题关联
            String[] questionIds = orderPaper.getQuestionIds();
            for (int i1 = 0; i1 < questionIds.length; i1++) {
                OrderPaperQuestion orderPaperQuestion = new OrderPaperQuestion();
                orderPaperQuestion.setPaperId(orderPaper.getId());
                orderPaperQuestion.setQuestionId(Integer.parseInt(questionIds[i1]));
                orderPaperQuestionService.insertOrderPaperQuestion(orderPaperQuestion);
            }
            //writeJSON(null, response, "200", "添加成功");
            return new ApiReturnObject("200", "添加成功", null);
        }
        return new ApiReturnObject("201", "传参有误", null);
    }

    //随机获取试题id
    private int random(int size, List<Integer> ran) {
        Integer i = 0;
        Random random = new Random();
        if (!ran.contains(i = random.nextInt(size))) {
            ran.add(i);
            return i;
        }
        return random(size, ran);
    }
}
